<template>
  <div class="dashboard">
    <SearchForm ref="searchFormcen" :data="propForm" :dataHandler="propHandler" />
    <PublicTable
      :isLoading="isLoading"
      :tableInfo="tableInfo"
      :pagination="true"
      :pageData="pageData"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <Dialog ref="dialog" :title="title" :buttons="buttons" @closeDialog="closeDialog" width="540px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="rigth">
        <el-form-item label="所属公司:" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择" filterable size="mini" style="width: 400px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户姓名:" prop="userName">
          <el-input placeholder="请输入用户姓名" v-model="form.userName" size="mini" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="userAccount">
          <el-input placeholder="请输入手机号" v-model="form.userAccount" size="mini" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email" size="mini" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="用户密码:" prop="userPassword">
          <el-input placeholder="请输入用户密码" v-model="form.userPassword" size="mini" style="width: 400px"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { listPage, modifyUser, modify, companyDelete, companyListPage } from "../../api/accountMng";
export default {
  data() {
    return {
      propForm: [
        {
          name: "账号",
          type: "input",
          key: "accountNumber",
          placeholder: "请输入账号",
          required: false,
          width: "100px",
        },
        {
          name: "用户名",
          type: "input",
          key: "userName",
          placeholder: "请输入用户名",
          required: false,
          width: "100px",
        },
        {
          name: "所属公司",
          type: "select",
          key: "companyId",
          placeholder: "请选择所属公司",
          required: false,
          selectList: [],
          prop: ['label', 'value']
        },
        {
          type: "button",
          button: [
            {
              name: "搜索",
              color: "primary",
              method: (c) => {
                this.searchData(c)
              },
            },
            {
              name: "清空",
              color: "info",
              method: (c) => {
                this.searchData(c, true)
              },
              clean: true,
            },
          ],
        },
      ],
      propHandler: [
        {
				  info: "新增账号",
				  icon: "el-icon-plus",
				  color: "#3370ff",
				  method: (c) => {
            this.title = '新增账号'
				    this.$refs.dialog.show()
				  },
				}, 
      ],
      tableInfo: {
        selectable: true,
        tableConfig: [
          {
            label: "ID",
            prop: "id",
          },
          {
            label: "账号",
            prop: "userAccount",
          },
          {
            label: "密码",
            prop: "userPassword",
          },
          {
            label: "用户名",
            prop: "userName",
          },
          {
            label: "角色",
            prop: "roleKeyVal",
          },
          {
            label: "账号状态",
            prop: "statusVal",
          },
          {
            label: "邮箱",
            prop: "email",
            width: 160
          },
          {
            label: "所属公司",
            prop: "companyName",
          },
          {
            type: "buttons",
            label: "操作",
            width: "200px",
            align: "center",
            fixed: "right",
            list: [
              {
                type: "success",
                text: "修 改",
                show: (row) => {
                  return row.roleKey != 'superAdmin' && row.status
                },
                events: (row) => {
                  this.form = row
                  this.title = '修改账号信息'
                  this.$refs.dialog.show()
                },
              },
              {
                type: "primary",
                text: "权 限",
                show: (row) => {
                  return row.roleKey != 'superAdmin' && row.status
                },
                events: (row) => {
                  let msg = row.roleKey == 'admin' ? `确定将"${row.userName}"变更为普通用户？` : `确定将"${row.userName}"变更为管理员？`
                  this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    modify({
                      isAdmin: row.roleKey == 'admin' ? 0 : 1,
                      status: row.status,
                      userId: row.id
                    }).then(res => {
                      if (res.code == 200) {
                        this.$message.success(res.message)
                        this.getList()
                      } else this.$message.error(res.message)
                    })
                  })
                },
              },
              {
                type: "warning",
                text: "启 用",
                show: (row) => {
                  return row.roleKey != 'superAdmin' && row.status
                },
                events: (row) => {
                  this.submit(row,1)
                },
              },
              {
                type: "warning",
                text: "禁 用",
                show: (row) => {
                  return row.roleKey != 'superAdmin' && !row.status
                },
                events: (row) => {
                  this.submit(row,2)
                },
              },
              {
                type: "danger",
                text: "删 除",
                show: (row) => {
                  return false
                },
                events: (row) => {
                  this.$confirm('确定删除该账号?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    companyDelete(row.id).then(res => {
                      if (res.code == 200) {
                        this.$message.success(res.message)
                        this.getList()
                      } else this.$message.error(res.message)
                    })
                  })
                },
              }
            ],
          },
        ],
        tableData: [],
      },
      pageData: {
        pindex: 1,
        psize: 10,
        total: 0,
      },
      searchDatas: {
        accountNumber: "",
      },
	    isLoading: false,
      title: '新增账号',
      buttons: [
        {
          type: "primary",
          title: "确认",
          loading: false,
          method: () => {
            this.submit()
          },
        },
        {
          title: "取消",
          method: () => {
            this.closeDialog()
            this.$refs.dialog.show()
          },
        },
      ],
      form: {
        userName: "",
        userAccount: "",
        userPassword: 'admin',
        companyId: "",
        email: '',
      },
      rules: {
        userName: { required: true, message: "请输入用户姓名", trigger: ['blur', 'change'] },
        userAccount: [{ required: true, message: "请输入手机号", trigger: ['blur', 'change']},
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] },
        ],
        userPassword: { required: true, message: "请输入用户密码", trigger: ['blur', 'change'] },
        companyId: { required: true, message: "请选择所属公司", trigger: ['blur', 'change'] },
        email: { required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
      },
      options: [],
    };
  },
  mounted() {
    this.getList()
    this.companyListPage()
  },
  methods: {
    //搜索
    searchData(c, close) {
      this.searchDatas.accountNumber = close ? "" : c.accountNumber;
      this.searchDatas.userName = close ? "" : c.userName;
      this.searchDatas.companyId = close ? "" : c.companyId;
      this.pageData.pindex = 1;
      this.getList();
    },
    //列表
    getList(tag) {
      let params = {
        page: this.pageData.pindex,
        pageSize: this.pageData.psize,
        ...this.searchDatas,
      };
      this.isLoading = true;
      listPage(params).then((res) => {
        this.isLoading = false;        
        if (res.code == 200) {
          this.tableInfo.tableData = res.data.data;
          this.tableInfo.tableData.forEach(i => {
            i.statusVal = i.status == 0 ? '正常' :  '禁用'
            i.roleKeyVal = i.roleKey == 'superAdmin' ? '超级管理员' : i.roleKey == 'admin' ? '管理员' : '普通用户'
          })
          this.pageData.total = res.data.total || 0;
        } else this.$message.error(res.message);
      });
    },
    // 获取公司
    companyListPage() {
      companyListPage({
        page: 1,
        pageSize: 9999
      }).then((res) => {   
        if (res.code == 200) {
          this.options = res.data.data.map(e => {
            return {
              label: e.companyName,
              value: e.id,
            }
          })
          if(sessionStorage.getItem('role') == 'superAdmin') this.propForm[2].selectList = this.options
        } else this.$message.error(res.message);
      });
    },
    //控制翻页
    handleCurrentChange(v) {
      this.pageData.pindex = v;
      this.getList();
    },
    //控制每页多少条
    handleSizeChange(num) {
      this.pageData.psize = num;
      this.getList();
    },
    //保存
    submit(row,number) {
      if(number) {
        let obj = {...row}
          obj.status = number - 1
          this.buttons[0].loading = true
          modifyUser(obj).then((res) => {
            if (res.code == 200) {
              let msg = number == 1 ? '启用成功' : '禁用成功'
              this.$message.success(msg)
              this.getList()
            } else this.$message.error(res.message)
            this.buttons[0].loading = false
          })
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.buttons[0].loading = true
            modifyUser(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.message)
                this.closeDialog()
                this.$refs.dialog.show()
                this.getList()
              } else this.$message.error(res.message)
              this.buttons[0].loading = false
              
            })
          }
        })
      }
    },
    closeDialog() {
      this.form = {
        userName: "",
        userAccount: "",
        userPassword: 'admin12345',
        companyId: "",
        email: '',
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
}
</style>
